package model

import (
	"fmt"
	"github.com/rs/zerolog/log"
	"shyxy-net/pkg/fiber"
	"shyxy-net/pkg/grpc"
)

func (ms *Service) GetRpcServerBackendByModelName(modelName string) (grpc.Backend, error) {
	var result fiber.Result
	var err error
	toModelBackendPath := func(modelName string) string {
		return fmt.Sprintf("/models/%s/rpc", modelName)
	}
	for i := 0; i < 3; i++ {
		err = ms.client.Get(toModelBackendPath(modelName), &result)
		if err == nil {
			break
		}
		log.Debug().Msgf("Attempt %d failed: %v", i+1, err)
	}

	if err != nil {
		return nil, err
	}

	if result.Code != 0 {
		return nil, fmt.Errorf("error msg:%s", result.Msg)
	}

	addressValue, exists := result.Data["address"]
	if !exists {
		return nil, fmt.Errorf("missing backend in data")
	}
	var address string
	switch v := addressValue.(type) {
	case string:
		address = v
	case nil:
		return nil, fmt.Errorf("backend address is nil")
	default:
		return nil, fmt.Errorf("unexpected backend address type: %T", v)
	}
	backend := grpc.NewClient(address, false, nil, false)
	return backend, nil
}
